package it.francescogabbrielli.android.solidalapp.actions;

import org.apache.http.HttpStatus;

import android.util.Log;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;

import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.Deviceendpoint;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.model.Device;

public class EndpointsGetDevice extends Action {
	
	private boolean loading;
	
	private Device device;
	
	@Override
	public void execute() throws Exception {
		
		Device currentDevice = (Device) app.getData(DataKey.DEVICE);
		if (currentDevice!=null)
			return;
		
		SolidalApp app = (SolidalApp) context.getApplicationContext();
		String regId = app.getStatus().getGcmId();
		if (regId==null)
			return;
		
		loading = true;
		
		try {
			Deviceendpoint endpoint = EndpointsUtils.buildEndpoint(Deviceendpoint.class);
			device = endpoint.getDeviceByRegistration(regId).execute();
			setModel(device);
		} catch(GoogleJsonResponseException re) {
			switch(re.getStatusCode()) {
			case HttpStatus.SC_NOT_FOUND:
//				if (currentDevice!=null)
//					reportCrash(regId, "Device not found?", re);
				Log.i(getClass().getSimpleName(), "Device not found? "+regId);
				break;
			default:
				throw re;
			}
		}
		
	}

	@Override
	public void onPostExecute() throws Exception {
		if (loading)
			if (device!=null) {
				app.setData(DataKey.DEVICE, device);
				if (!app.isUpToDate())
					Action.start(context, EndpointsUpdateDevice.class, device);
			} else if (app.getData(DataKey.DEVICE)==null) {
				start(context, EndpointsInsertDevice.class);
			}
	}

}
